/**
 * @Description:
 * @Author BPF
 * @create 2021/8/24 18:06
 */
import NProgress from 'nprogress'
import store from '@/store/index'
import routes, { backsysRoutes } from './routes'
import { teacher } from './roles'
import { generateNavAttr } from '@bianpengfei/b-ui/lib/_util/router-cache'
import { MessageBox } from 'element-ui'
import { cloneDeep } from 'lodash-es'
import { deepClone, isFunction, uuid } from '@bianpengfei/utils'
import Detail1 from '@/views/template/components/detail-1/index'

const whiteList = [
  // 白名单
  'authorization'
]

let _loadingDOM = document.querySelector('#app-loading__index')

/**
 * loading 加载
 * @param status
 * @returns {*}
 */
export const toastLoading = (status = true) => {
  _loadingDOM ||= document.querySelector('#app-loading__index')
  if (_loadingDOM) _loadingDOM.style.display = status ? 'inline-block' : 'none'
}

/**
 * 自动化生成路由 name，根据path
 * @param routes
 * @returns {*[]}
 */
export const generateRouteName = (routes = []) => {
  if (Array.isArray(routes)) {
    routes.forEach((route) => {
      route.name ||= route.path.replaceAll('/', '_').slice(route.path.startsWith('/') ? 1 : 0)
      generateRouteName(route?.children)
    })
  }
  return routes
}

/**
 * 生成路由权限
 * @param asyncRoutes
 * @param names
 */
export const generateRoutes = (asyncRoutes = [], names = []) => {
  const asyncRoutesClone = JSON.parse(JSON.stringify(asyncRoutes))
  const hasPermission = (permissionCodes, route) => {
    if (route.name) {
      return permissionCodes.includes(route.name)
    } else {
      return true
    }
  }
  const filterAsyncRoutes = (routes, permissionCodes, result = []) => {
    routes.forEach((route) => {
      const tmp = route
      delete tmp.component
      if (hasPermission(permissionCodes, tmp)) {
        if (Array.isArray(tmp.children)) {
          tmp.children = filterAsyncRoutes(tmp.children, permissionCodes)
        }
        result.push(tmp)
      }
    })
    return result
  }
  return filterAsyncRoutes(asyncRoutesClone, names)
}

/**
 * 转化菜单格式
 * @param {Array} routes
 * @returns {*}
 */
export const transferMenus = (routes = []) => {
  if (Array.isArray(routes)) {
    routes.forEach((v) => {
      v.component && delete v.component
      v = {
        ...v,
        ...generateNavAttr(v)
      }
      if (Array.isArray(v.children)) {
        v.children.length == 0 ? delete v.children : transferMenus(v.children)
      }
    })
  }
  return routes
}

/**
 * 退出登录
 * @param title
 * @param content
 * @returns {Promise<MessageBoxData>}
 */
export const signOutFn = (title = '警告', content = '登录已过期, 请重新登录') =>
  MessageBox.alert(content, title, {
    confirmButtonText: '确定',
    showClose: false,
    type: 'warning',
    closeOnClickModal: false,
    callback: (action) => action == 'confirm' && store.dispatch('user/logOut')
  })

console.log(Detail1)

export const routerGuard = async function () {
  await store.dispatch('app/setDynamicRoutes', transferMenus(backsysRoutes))

  this.beforeEach(async (to, from, next) => {
    console.log(this.resolve(to.path), this.getRoutes())
    NProgress.start()
    if (whiteList.includes(to.name) || to.meta?.auth === false) {
      next()
    } else {
      next()
      // const accessToken = store.get('user/accessToken')
      // const userInfo = store.get('user/info')
      // if (accessToken) {
      //   try {
      //     // 如果token存在
      //     if (userInfo?.userCode) {
      //       // 如果用户信息存在
      //       next()
      //     } else {
      //       // 用户信息不存在，重新去请求拉取用户信息
      //       toastLoading(true)
      //       const { appPermissions } = await store.dispatch('user/getUserInfo')
      //       await store.dispatch('app/setDynamicRoutes', transferMenus(backsysRoutes))
      //       toastLoading(false)
      //       next({ ...to, replace: true })
      //     }
      //   } catch (e) {
      //     console.error('路由跳转错误', e)
      //     toastLoading(false)
      //     signOutFn()
      //   }
      // } else {
      //   // 如果token不存在，跳转到统一登录
      //   // signOutFn()
      //   console.error('用户信息失效')
      //   signOutFn()
      // }
    }
  })

  // eslint-disable-next-line no-unused-vars
  this.afterEach((to, from, next) => {
    NProgress.done()
  })
}
